﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Data;
using System.Drawing;
using System.Configuration;

public partial class RejectAppSubmitPopupForm : System.Web.UI.Page
{
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESRejectAppBusiness rejectapp = new uMESRejectAppBusiness();
    string webRootDir = HttpRuntime.AppDomainAppPath;
    string webRootUrl = "~";
    string businessName = "质量管理", parentName = "rejectappinfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            Dictionary<string, object> popupData = (Dictionary<string, object>)Session["PopupData"];
            txtDispContainerID.Text = popupData["ContainerID"].ToString();
            txtDispProcessNo.Text = popupData["ProcessNo"].ToString();
            txtDispOprNo.Text = popupData["OprNo"].ToString();
            txtDispContainerName.Text = popupData["ContainerName"].ToString();
            txtDispProductName.Text = popupData["ProductName"].ToString();
            txtDispDescription.Text = popupData["Description"].ToString();
            txtDispContainerQty.Text = popupData["ContainerQty".ToString()].ToString();
            txtDispSpecID.Text = popupData["SpecID"].ToString();
            txtDispPlannedStartDate.Text = popupData["PlannedStartDate"].ToString();
            txtDispPlannedCompletionDate.Text = popupData["PlannedCompletionDate"].ToString();
            txtWorkflowID.Text = popupData["WorkflowID"].ToString();
            txtSpecName.Text = popupData["SpecName"].ToString();

            DataTable dtQualityRecord = (DataTable)(popupData["dtQualityRecord"]);
            Session["dtQualityRecord"] = dtQualityRecord;

            //DataTable dtProductNo = (DataTable)(popupData["dtProductNo"]);
            //Session["dtProductNo"] = null;// dtProductNo;

            int intQty = 0;
            foreach (DataRow row in dtQualityRecord.Rows)
            {
                intQty += Convert.ToInt32(row["Qty"]);
            }

            txtQty.Text = intQty.ToString();

            Session["PopupData"] = null;

            txtRejectAppInfoName.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            GetRejectReason();
            GetDesignEmployee();

            //显示质量信息描述
            string notes = popupData["QualityNotes"].ToString();
            string disNotes=""; ParseCode(notes, ref disNotes);
            txtQualityNotes.Text = disNotes;
            //责任部门
            BindResponsibleDepartment();
        }
    }

    #region 绑定责任部门
    protected void BindResponsibleDepartment()
    {
        DataTable dt = common.GetFactoryNames();
        ddlResponsibleDepartment.DataTextField = "factoryname";
        ddlResponsibleDepartment.DataValueField = "factoryid";
        ddlResponsibleDepartment.DataSource = dt;
        ddlResponsibleDepartment.DataBind();

        ddlResponsibleDepartment.Items.Insert(0, "");
    }
    #endregion

    #region 获取不合格原因
    protected void GetRejectReason()
    {
        DataTable DT = common.GetRejectReason();

        ddlRejectReason.DataTextField = "RejectReasonName";
        ddlRejectReason.DataValueField = "RejectReasonID";
        ddlRejectReason.DataSource = DT;
        ddlRejectReason.DataBind();

        ddlRejectReason.Items.Insert(0, string.Empty);
    }
    #endregion

    #region 获取设计/工艺人员
    protected void GetDesignEmployee()
    {
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strFactoryID = userInfo["FactoryID"];
        string strEmployeeID = userInfo["EmployeeID"];
        DataTable DT = rejectapp.GetDesignEmployee(strFactoryID, strEmployeeID);
        //工艺员
        ddlDesignEmployee.DataTextField = "FullName";
        ddlDesignEmployee.DataValueField = "EmployeeID";
        ddlDesignEmployee.DataSource = DT;
        ddlDesignEmployee.DataBind();

        ddlDesignEmployee.Items.Insert(0, "");
        //设计院
        ddlDesignEmp2.DataTextField = "FullName";
        ddlDesignEmp2.DataValueField = "EmployeeID";
        ddlDesignEmp2.DataSource = DT;
        ddlDesignEmp2.DataBind();

        ddlDesignEmp2.Items.Insert(0, "");
    }
    #endregion

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        lStatusMessage.Text = strMessage;

        if (boolResult == true)
        {
            lStatusMessage.ForeColor = Color.Black;
        }
        else
        {
            lStatusMessage.ForeColor = Color.Red;
        }
    }
    #endregion

    #region 提交按钮
    protected void btnMaterialApp_Click(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        //string strTest = GetCode();
        //ShowStatusMessage(strTest, false);
        //return;

        try
        {
            string strRejectReasonID = ddlRejectReason.SelectedValue;
            if (strRejectReasonID == string.Empty)
            {
                ShowStatusMessage("请选择不合格原因", false);
                return;
            }
            //add:Wangjh 20201102
            if (string.IsNullOrWhiteSpace(ddlDesignEmployee.SelectedValue) && string.IsNullOrWhiteSpace(ddlDesignEmp2.SelectedValue))
            {
                ShowStatusMessage("请选择工艺员或设计员", false);
                return;
            }
            else if (!string.IsNullOrWhiteSpace(ddlDesignEmployee.SelectedValue) && !string.IsNullOrWhiteSpace(ddlDesignEmp2.SelectedValue)) {
                ShowStatusMessage("工艺员和设计员只能选择一个", false);
                return;
            }
            //
            if (string.IsNullOrWhiteSpace(ddlResponsibleDepartment.SelectedValue)) {
                ShowStatusMessage("请选择责任部门", false);
                return;
            }

            string qualityNotes = GetCode();

            string strRejectAppInfoName = txtRejectAppInfoName.Text;
            string strContainerID = txtDispContainerID.Text;
            string strSpecID = txtDispSpecID.Text;
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strSubmitEmployeeID = userInfo["EmployeeID"];
            string strQty = txtQty.Text;
            string strDesignEmployeeID = ddlDesignEmployee.SelectedValue;
            string strQualityNotes = qualityNotes;// txtQualityNotes.Text.Trim();

            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("RejectAppInfoName", strRejectAppInfoName);
            para.Add("ContainerID", strContainerID);
            para.Add("SpecID", strSpecID);
            para.Add("SubmitEmployeeID", strSubmitEmployeeID);
            para.Add("SubmitDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            para.Add("SubmitNotes", "");
            para.Add("Qty", strQty);
            para.Add("UOMID", "");
            para.Add("RejectReasonID", strRejectReasonID);
            para.Add("DesignEmployeeID", strDesignEmployeeID);
            para.Add("QualityNotes", strQualityNotes);
            para.Add("Notes", "");
            para.Add("DesignEmpID", ddlDesignEmp2.SelectedValue);//add:Wangjh 设计人员
            para.Add("ResponsiDepart", ddlResponsibleDepartment.SelectedValue);//add:Wangjh 责任部门
            para["RejectappInfoID"] = Guid.NewGuid().ToString();

            if (!string.IsNullOrWhiteSpace(para["DesignEmpID"]))//存在设计人员审核，设计审核->工艺审核
            {
                para.Add("Status", "5");
            }
            else {
                para.Add("Status", "10");
            }
            //增加工艺规程
            para.Add("WorkflowID", txtWorkflowID.Text);

            DataTable dtQualityRecord = (DataTable)Session["dtQualityRecord"];

            DataTable dtProductNo = common.GetProductNoByQRIDList(dtQualityRecord);

            //dtProductNo.Columns.Add("Qty");
            dtProductNo.Columns.Add("UOMID");
            dtProductNo.Columns.Add("DisposeResult");
            dtProductNo.Columns.Add("LossReasonID");
            dtProductNo.Columns.Add("DisposeAdviceID");
            dtProductNo.Columns.Add("DisposeNotes");
            dtProductNo.Columns.Add("QualityNotes");
            dtProductNo.Columns.Add("Notes");

            foreach (DataRow row in dtProductNo.Rows)
            {
                // row["Qty"] = "1";
                row["QualityNotes"] = qualityNotes;//txtQualityNotes.Text;
            }

            rejectapp.AddRejectAppInfo(para, dtQualityRecord, dtProductNo);

            #region 记录日志
            var ml = new MESAuditLog();
            ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtDispContainerID.Text;
            ml.ParentID = para["RejectappInfoID"]; ml.ParentName = parentName;
            ml.CreateEmployeeID = userInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 0;
            ml.Description = "不合格审理:" + txtSpecName.Text + ",不合格记录提交" ;
            common.SaveMESAuditLog(ml);
            #endregion

            Session["dtQualityRecord"] = null;
            Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    #region 特殊字符转换

    public void ParseCode(String strPreviewCode, ref string strPreviewCodeDis)
    {
        try
        {
            String strPreviewCodeTemp, strHtmlStripped, strTemp, strCodeTemp;
            String strFileDoc, strFileTemp, strFilePath, strFileName, strMapPath, strHtml;
            int intStartFlag, intEndFlag, intFlag1, intFlag2, intCodeStartFlag, intCodeEndFlag;
            String strImageIndex;
            clsParseCode oParse = new clsParseCode();
            Bitmap objBmp;
            String strLeft, strUp, strDown, strRight;

            strPreviewCode = strPreviewCode.Trim().Replace("\r\n\t\t", "");
            strPreviewCode = strPreviewCode.Trim().Replace("<P>", "");
            strPreviewCode = strPreviewCode.Trim().Replace("</P>", "");
            strPreviewCode = strPreviewCode.Replace("\"", "'");

            intStartFlag = strPreviewCode.IndexOf("<Image>");
            intEndFlag = strPreviewCode.IndexOf("</Image>");
            strHtmlStripped = "";
            strHtml = "";

            //strMapPath = MapPath("~");
            //strFileTemp = strMapPath + @"\Images\";

            //clsCon oCon = new clsCon();
            String strImagePath;
            //strImagePath = oCon.LoadConfigString("ImageGetPath");

            strImagePath = webRootDir + ConfigurationManager.AppSettings["ImageGetPath"].ToString();

            strFileTemp = strImagePath;

            uMESExternalControl.ToleranceInputLib.clsDrawImage oDraw = new uMESExternalControl.ToleranceInputLib.clsDrawImage();
            DataTable dtImage = new DataTable();

            while (intStartFlag > -1)
            {
                if (intStartFlag > 0)
                {
                    //将纯文本输出
                    strHtml = strPreviewCode.Substring(0, intStartFlag);
                    strPreviewCode = strPreviewCode.Substring(intStartFlag);
                    strPreviewCodeDis += strHtml;
                    intStartFlag = strPreviewCode.IndexOf("<Image>");
                    intEndFlag = strPreviewCode.IndexOf("</Image>");
                    continue;
                }

                else
                {
                    strHtml = "";
                    strPreviewCodeTemp = strPreviewCode.Substring(intStartFlag + 7, intEndFlag - intStartFlag - 7);
                    intCodeStartFlag = strPreviewCodeTemp.IndexOf("<&70><+>");
                    intCodeEndFlag = strPreviewCodeTemp.IndexOf("<+><&90>");

                    if (intCodeStartFlag > -1)
                    {
                        //代码为行位公差时
                        strCodeTemp = strPreviewCodeTemp.Replace("<&70><+>", "");
                        strCodeTemp = strCodeTemp.Replace("<+><&90>", "");

                        intFlag1 = strCodeTemp.IndexOf("<");
                        intFlag2 = strCodeTemp.IndexOf(">");
                        while (intFlag1 > -1)
                        {
                            strTemp = strCodeTemp.Substring(intFlag1, intFlag2 - intFlag1 + 1);
                            strCodeTemp = strCodeTemp.Replace(strTemp, "");
                            intFlag1 = strCodeTemp.IndexOf("<");
                            intFlag2 = strCodeTemp.IndexOf(">");
                        }

                        strHtmlStripped = strCodeTemp;
                        //strPreviewCodeTemp = strPreviewCode;
                        strPreviewCodeTemp = strPreviewCodeTemp.Replace(@"<Image>", "");
                        strPreviewCodeTemp = strPreviewCodeTemp.Replace(@"</Image>", "");

                        objBmp = oDraw.DrawShapeTolerance(strPreviewCodeTemp, strHtmlStripped, strFileTemp);
                    }
                    else
                    {
                        intCodeStartFlag = strPreviewCodeTemp.IndexOf("<T");
                        intCodeEndFlag = strPreviewCodeTemp.IndexOf("!");
                        if (intCodeStartFlag > -1)
                        {
                            //代码为上下标公差

                            strLeft = strPreviewCodeTemp.Substring(0, intCodeStartFlag);
                            strUp = strPreviewCodeTemp.Substring(intCodeStartFlag + 2, intCodeEndFlag - intCodeStartFlag - 2);
                            strDown = strPreviewCodeTemp.Substring(intCodeEndFlag + 1, strPreviewCodeTemp.Length - intCodeEndFlag - 2);
                            objBmp = oDraw.DrawTolerance(strLeft, strUp, strDown);
                        }
                        else
                        {
                            intCodeStartFlag = strPreviewCodeTemp.IndexOf("<H>");
                            intCodeEndFlag = strPreviewCodeTemp.IndexOf("</H>");
                            if (intCodeStartFlag > -1)
                            {
                                //代码为只有上公差
                                strLeft = strPreviewCodeTemp.Substring(0, intCodeStartFlag);
                                strUp = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);
                                strDown = "";
                                objBmp = oDraw.DrawTolerance(strLeft, strUp, strDown);
                            }
                            else
                            {
                                intCodeStartFlag = strPreviewCodeTemp.IndexOf("<L>");
                                intCodeEndFlag = strPreviewCodeTemp.IndexOf("</L>");
                                if (intCodeStartFlag > -1)
                                {
                                    //代码为只有下公差
                                    strLeft = strPreviewCodeTemp.Substring(0, intCodeStartFlag);
                                    strUp = "";
                                    strDown = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);
                                    objBmp = oDraw.DrawTolerance(strLeft, strUp, strDown);
                                }
                                else
                                {
                                    intCodeStartFlag = strPreviewCodeTemp.IndexOf("<√>");
                                    intCodeEndFlag = strPreviewCodeTemp.IndexOf("</√>");
                                    if (intCodeStartFlag > -1)
                                    {
                                        //代码为指定加工方法时
                                        strLeft = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);

                                        strRight = strPreviewCodeTemp.Substring(intCodeEndFlag + 4);
                                        objBmp = oDraw.DrawRoughness(strLeft, strRight);
                                    }
                                    else
                                    {
                                        intCodeStartFlag = strPreviewCodeTemp.IndexOf("<R>");
                                        intCodeEndFlag = strPreviewCodeTemp.IndexOf("</R>");
                                        if (intCodeStartFlag > -1)
                                        {
                                            //代码为去除材料时
                                            strLeft = strPreviewCodeTemp.Substring(intCodeStartFlag + 3, intCodeEndFlag - intCodeStartFlag - 3);

                                            strRight = "";
                                            objBmp = oDraw.DrawRoughness(strLeft, strRight);
                                        }
                                        else
                                        {
                                            intCodeStartFlag = strPreviewCodeTemp.IndexOf("<Q>");
                                            intCodeEndFlag = strPreviewCodeTemp.IndexOf("</Q>");
                                            if (intCodeStartFlag > -1)
                                            {
                                                //代码为不去除材料时
                                                strLeft = "";

                                                strRight = "";
                                                objBmp = oDraw.DrawRoughness(strLeft, strRight);
                                            }
                                            else
                                            {
                                                objBmp = null;
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }

                    //保存
                    if (objBmp != null)
                    {
                        //strFileDoc = strMapPath + @"\ImageTemp\";
                        //clsCon oCon = new clsCon();
                        String strImageTempPath;
                        //strImageTempPath = oCon.LoadConfigString("ImageTempPath");
                        strImageTempPath = webRootDir + ConfigurationManager.AppSettings["ImageTempPath"].ToString();

                        strFileDoc = strImageTempPath;
                        //if (Session["intMaxImageIndex"] == null)
                        //{
                        //    Session["intMaxImageIndex"] = 0;
                        //    intImageIndex = 1;
                        //}
                        //else
                        //{
                        //    intImageIndex = (int)Session["intMaxImageIndex"] + 1;
                        //}

                        strImageIndex = System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff");
                        strFileName = "ImageTemp-" + strImageIndex + ".png";
                        //strFileName = "ImageTemp-" + intImageIndex + ".png";
                        strFilePath = strFileDoc + strFileName;
                        //System.Threading.Thread.Sleep(1);
                        //System.IO.FileInfo oFile = new System.IO.FileInfo(strFilePath);
                        //while (oFile.Exists == true)
                        //{
                        //    intImageIndex += 1;
                        //    strFileName = "ImageTemp-" + intImageIndex + ".png";
                        //    strFilePath = strFileDoc + strFileName;
                        //    oFile = new System.IO.FileInfo(strFilePath);
                        //}

                        System.IO.FileInfo oFile = new System.IO.FileInfo(strFilePath);
                        while (oFile.Exists == true)
                        {
                            strImageIndex = strImageIndex + "1";
                            strFileName = "ImageTemp-" + strImageIndex + ".png";
                            strFilePath = strFileDoc + strFileName;
                            oFile = new System.IO.FileInfo(strFilePath);
                        }

                        objBmp.Save(strFilePath);
                        // Session["intMaxImageIndex"] = intImageIndex;
                        if (Session["dtImage"] == null)
                        {
                            dtImage = new DataTable();
                            dtImage.Columns.Add("FileName");
                            dtImage.Columns.Add("HtmlCode");
                            Session["dtImage"] = dtImage;
                        }
                        else
                        {
                            dtImage = (DataTable)Session["dtImage"];
                        }

                        DataRow dr;
                        dr = dtImage.NewRow();
                        dr[0] = strFileName;
                        dr[1] = "<Image>" + strPreviewCodeTemp + "</Image>";
                        dtImage.Rows.Add(dr);
                        Session["dtImage"] = dtImage;

                        //strFileDoc = oCon.LoadConfigString("ImageTempPath");
                        //strFileDoc = ConfigurationManager.AppSettings["ImageTempPath"].ToString();
                        strFileDoc = ResolveUrl(webRootUrl + ConfigurationManager.AppSettings["ImageTempPath"].ToString());

                        // strHtml = "<img src='../../../ImageTemp/" + strFileName + "'>";
                        strHtml = @"<img src='" + strFileDoc + strFileName + "'>";
                        strPreviewCodeDis += strHtml;
                    }

                }
                if (intEndFlag + 8 < strPreviewCode.Length)
                {
                    strPreviewCode = strPreviewCode.Substring(intEndFlag + 8);
                    intStartFlag = strPreviewCode.IndexOf("<Image>");
                    intEndFlag = strPreviewCode.IndexOf("</Image>");
                }
                else
                {
                    intStartFlag = -1;
                }

            }
            intStartFlag = strPreviewCode.IndexOf("<Image>");
            if (strPreviewCode != "" && intStartFlag == -1)
            {
                strPreviewCodeDis += strPreviewCode;
            }
        }
        catch (Exception myError)
        {

        }

    }


    public String GetCode()
    {
        String strHtmlCode, strHtml, strHtmlTemp;
        try
        {
            DataTable dtImage = new DataTable();
            int i, intStartFlag, intEndFlag;
            dtImage = (DataTable)Session["dtImage"];

            strHtml = txtQualityNotes.Text.Trim();
            strHtmlCode = strHtml;

            intStartFlag = strHtmlCode.IndexOf("<img");
            if (intStartFlag == -1)
            {
                intStartFlag = strHtmlCode.IndexOf("<IMG");
            }
            if (intStartFlag > -1)
            {
                intEndFlag = strHtmlCode.IndexOf(">", intStartFlag);
                ;
            }
            else
            {
                intEndFlag = -1;
            }

            if (dtImage != null)
            {
                if (dtImage.Rows.Count > 0)
                {
                    while (intStartFlag > -1)
                    {
                        strHtmlTemp = strHtmlCode.Substring(intStartFlag, intEndFlag - intStartFlag + 1);
                        for (i = 0; i <= dtImage.Rows.Count - 1; i++)
                        {
                            if (strHtmlTemp.IndexOf(@"/" + dtImage.Rows[i][0]) > -1)
                            {
                                strHtmlCode = strHtmlCode.Replace(strHtmlTemp, (String)dtImage.Rows[i][1]);
                                break;
                            }

                        }

                        intStartFlag = strHtmlCode.IndexOf("<img", intStartFlag + 1);
                        if (intStartFlag == -1)
                        {
                            intStartFlag = strHtmlCode.IndexOf("<IMG", intStartFlag + 1);
                        }
                        if (intStartFlag > -1)
                        {
                            intEndFlag = strHtmlCode.IndexOf(">", intStartFlag + 1);
                            ;
                        }
                        else
                        {
                            intEndFlag = -1;
                        }
                        //intEndFlag = strHtmlCode.IndexOf(">", intStartFlag + 1);
                    }

                }

            }

            return strHtmlCode;
        }
        catch (Exception myError)
        {
            ShowStatusMessage(myError.Message,false);
            return "";
        }
    }
    #endregion
}